uniform sampler2D	defPosTex;
uniform sampler2D	defNormalTex;
//uniform sampler2D	defColorTex;

varying	vec2	vPos;
varying	vec3	lPos;

uniform	vec4	lightColor;
uniform float	lightRange;

uniform float	distToCam;

#ifdef EMISSIVE
varying	vec2	vPPos;
varying	vec2	lPPos;
#endif

//-----------------------------------------------------------------------------

vec3	unpackPos( vec3 pos )
{
	//return (pos - 0.5) * 100.0;	//[-50;50]
	return (pos - 0.5) * 40.0;		//[-20;20]
}

//-----------------------------------------------------------------------------

vec3	unpackNormal( vec3 norm )
{
	return (norm - 0.5) * 2.0;
}

//-----------------------------------------------------------------------------

void main()
{
	//gl_FragData[0] = vec4( lightColor.rgb, lightRange );
	//return;

	//discard la ce e pe fundul ecranului
	//vec4 depth = texture2D( tex0, vPos );
	//if(depth.x > 0.99)
	//{
	//	discard;
	//}

#ifdef EMISSIVE
	float lightEmissiveRange = lightRange * 0.25 / distToCam;
	float em = ( lightEmissiveRange - clamp(distance( vPPos, lPPos ), 0.0, lightEmissiveRange ) ) / lightEmissiveRange * 0.6;
#endif

	//pozitie
	vec3 pos = unpackPos( texture2D( defPosTex, vPos ).xyz );

	//attenuare
	//float d = max(0, (lightRange - distance( lPos, pos )) * (1/lightRange));
	float d = ( lightRange - distance( lPos, pos ) ) / lightRange;
	//discard pe atenuare
	//if( d < 0 )
	//{
	//	discard;
	//}
	//gl_FragData[0] = vec4( vec3(d), 0.0 );
	//return;

	//normala
	vec3 N = unpackNormal( texture2D( defNormalTex, vPos ).xyz );
	//gl_FragData[0] = vec4( N, 0 );
	//return;

	//difuza
	vec3 L = normalize( lPos - pos );
	float NdotL = dot( N, L );
	float s = max( NdotL, 0 );
	//gl_FragData[0] = vec4( vec3(s), 0 );
	//return;

	//speculara
	//TODO trebuie refacut ca sa lucreze cu valori in M, nu in MV
	vec3 I = normalize( -pos );
	vec3 R = normalize ( reflect ( -L, N ) );
	float specularPower = 1.2;
	float t = pow ( max ( dot ( R , I ), 0.0 ), specularPower );
	//gl_FragData[0] = vec4( vec3(t), 0 );
	//return;

	//culoare finala
	float fact = (s * 1.0 + t * 0.75) * d;
#ifdef EMISSIVE
	fact += em;
#endif
	vec4 color = fact * lightColor;
	//vec4 color = (s * 1.0 + t * 0.75) * vec4(1.0) * d;

	gl_FragColor = color;
	//gl_FragColor = lightColor;
	//gl_FragColor = vec4( 1.0, 0.0, 0.0, 0.0 );
}